const ecUI = require('../../../utils/ecUI.js')
const ecBLE = require('../../../utils/ecBLE.js')
let ctx
let isCheckRevHex = false

Page({
    data: {
        deviceListData: [],
        deviceListDataShow: [],
        deviceSn:"BT_ECB1AC0007A2",
        textRevData: '',
        ballNumList:[],
    },
    onLoad(options) {
       var deviceSn=options.deviceSn;
       this.setData({deviceSn:deviceSn});
        ctx = this
        setInterval(() => {
            ctx.setData({ deviceListDataShow: ctx.data.deviceListData })
        }, 400)
    },
    onShow() {
        ctx.setData({ deviceListData: [] })
        ctx.setData({ deviceListDataShow: [] })
        ctx.openBluetoothAdapter()
        /* setTimeout(() => {
            ctx.openBluetoothAdapter()
        }, 100) */
    },
    onPullDownRefresh: function () {
        ctx.setData({ deviceListData: [] })
        ctx.setData({ deviceListDataShow: [] })
        setTimeout(() => {
            wx.stopPullDownRefresh()
            ctx.openBluetoothAdapter()
        }, 500)
    },
    listViewTap(event) {
      var that=this;
      console.log(event);
        //secUI.showLoading('设备连接中')
        ecBLE.onBLEConnectionStateChange(res => {
            ecUI.hideLoading()
            if (res.ok) {
                ecBLE.stopBluetoothDevicesDiscovery()
                //wx.navigateTo({ url: '../device/device' })
            } else {
                ecUI.showModal(
                    '提示',
                    '连接失败,errCode=' + res.errCode + ',errMsg=' + res.errMsg
                )
            }
        })
        var a={"type":"2","id":"04","state":"4","num":"2283634614"};
       // const device = event.currentTarget.dataset.name
        ecBLE.createBLEConnection(event.id).then(res=>{
          ecBLE.onBLECharacteristicValueChange((str, strHex) => {
            let data =
                ctx.data.textRevData +(isCheckRevHex ? strHex.replace(/[0-9a-fA-F]{2}/g, ' $&') : str) +'\r\n'
             console.log(data)
             data=data.replace("id:\"","id\":\"");
            ctx.setData({ textRevData: data })
            console.log("转json前："+data)
            var comJson=JSON.parse(data);
            console.log("转json后："+comJson)
            var number=comJson.num;
            var ballNumList=that.data.ballNumList;
            if(!number.startsWith('000000')){
                  var flag=true;
                  for(var i=0;i<ballNumList.length;i++){
                    if(number==ballNumList[i]){
                      flag=false;
                      break;
                    }
                  }
                  if(flag) {
                    ballNumList.push(number);
                    that.setData({ballNumList:ballNumList})
                  }
            }
        })
        })
    },
    openBluetoothAdapter() {
        ecBLE.onBluetoothAdapterStateChange(res => {
            if (res.ok) {
                console.log('Bluetooth adapter ok')
                ctx.startBluetoothDevicesDiscovery()
            } else {
                ecUI.showModal(
                    '提示',
                    `Bluetooth adapter error | ${res.errCode} | ${res.errMsg}`,
                    () => {
                        if (res.errCode === 30001) {
                            wx.openSystemBluetoothSetting()
                        }
                        if (res.errCode === 30003) {
                            wx.openAppAuthorizeSetting()
                        }
                        if (res.errCode === 30004) {
                            //跳转到小程序设置界面
                            wx.openSetting()
                        }
                    }
                )
            }
        })
        ecBLE.openBluetoothAdapter()
    },
    startBluetoothDevicesDiscovery() {
        console.log('start search')
        var that=this;
        ecBLE.onBluetoothDeviceFound(res => {
            // if(res.id==="EC:22:05:13:78:49")
            // console.log(`id:${res.id},name:${res.name},rssi:${res.rssi}`)
            for (const item of ctx.data.deviceListData) {
                if (item.id === res.id) {
                    item.name = res.name
                    item.rssi = res.rssi
                    return
                }
            }
            let manufacturer = ''
            if (res.name.length === 11 && res.name.startsWith('@')) {
                manufacturer = 'eciot'
            }
            if (res.name.length === 15 && res.name.startsWith('BT_')) {
                manufacturer = 'eciot'
                that.listViewTap(res);
            }
            ctx.data.deviceListData.push({
                id: res.id,
                name: res.name,
                rssi: res.rssi,
                manufacturer,
            })
            /*
            if(that.data.deviceSn==res.name){
              that.listViewTap(res);
            }*/
        })
        ecBLE.startBluetoothDevicesDiscovery()
    },
    onUnload() {
      ecBLE.onBLEConnectionStateChange(() => { })
      ecBLE.onBLECharacteristicValueChange(() => { })
      ecBLE.closeBLEConnection()
  },
})
